import React from 'react';
import Flex from 'antd-mobile/lib/flex';
import Button from 'antd-mobile/lib/button';

import 'antd-mobile/lib/button/style/index.css'
import 'antd-mobile/lib/flex/style/index.css'

import '../static/styles/chat.css';
import '../static/icon/icon.css'

import { get } from  '../api/getData';

const appkey = 'kj7swf8oki282';
let token = '';


let ChatLeft = React.createClass({
    getInitialState:function () {
        console.log(this.props);
        return this.state = {
            nickname : this.props.data.nickname,
            headimg : this.props.data.headimg,
            content : this.props.data.content,
        }
    },
    render: function () {
        return (
            <Flex className="chat-item-box">
                <Flex.Item>
                    <div className="chat-head">
                        <img src={this.state.headimg} alt=""/>
                    </div>
                </Flex.Item>
                <Flex.Item className="chat-item-box-right">
                    <Flex direction="column" justify="start" align="start" className="chat-item-box-content">
                        <Flex.Item  style={{width:'100%'}}>
                            <Flex direction="row" justify="around" className="chat-item-box-user">
                                <Flex.Item>
                                    <div className="chat-item-box-user-name">{this.state.nickname}</div>
                                </Flex.Item>
                            </Flex>
                        </Flex.Item>
                        <Flex.Item>
                            <div className="chat-item-content">{this.state.content}</div>
                        </Flex.Item>
                    </Flex>
                </Flex.Item>
            </Flex>
        )
    }
});

let ChatRight = React.createClass({
    getInitialState:function () {
        return this.state = {
            nickname : this.props.data.nickname,
            headimg : this.props.data.headimg,
            content : this.props.data.content,
        }
    },
    render: function () {
        return (
            <Flex className="chat-item-box">
                <Flex.Item className="chat-item-box-right">
                    <Flex direction="column" justify="start" align="start" className="chat-item-box-content-right">
                        <Flex.Item  style={{width:'100%'}}>
                            <Flex direction="row" justify="around" className="chat-item-box-user">
                                <Flex.Item>
                                    <div className="chat-item-box-user-name-right">{this.state.nickname}</div>
                                </Flex.Item>
                            </Flex>
                        </Flex.Item>
                        <Flex.Item>
                            <div className="chat-item-content-right">{this.state.content}</div>
                        </Flex.Item>
                    </Flex>
                </Flex.Item>
                <Flex.Item>
                    <div className="chat-head">
                        <img src={this.state.headimg} alt=""/>
                    </div>
                </Flex.Item>
            </Flex>
        )
    }
});

class Chat extends React.Component {
    constructor(props) {
        super(props);
        let sendData = {
            headimg : 'http://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eryD105ZeVRbiaehGr2tuiaYgZicSiaJ1vEKE0yjoicibNHFRd12elUQluhEHByic7YjVE3DiaQX7DfYfR0ew/0',
            nickname : '测试',
            content : '测试测试'
        };
        this.state = {
            input:'',
            chat : [
                <ChatRight data={sendData}/>,
                <ChatLeft data={sendData}/>,
                <ChatLeft data={sendData}/>,
                <ChatLeft data={sendData}/>,
                <ChatRight data={sendData}/>,
                <ChatLeft data={sendData}/>,
                <ChatRight data={sendData}/>,
                <ChatLeft data={sendData}/>,
                <ChatRight data={sendData}/>
            ]
        };
    }

    send(){
        let newChat = this.state.chat;
        let sendData = {
            headimg : 'http://wx.qlogo.cn/mmopen/vi_32/xQpY1triag0T0BA5fPpGcOxicEicKcgSvicVV1bR4A0UbdiaA3xvKMeGwVB5UIY5AsfJU8j1a1sXcS790MFJ6kZoA0g/0',
            nickname : '测试',
            content : this.state.input
        };
        let type = 'left';
        if(type === 'left') {
            newChat.push(<ChatLeft data={sendData}/>);
        }else{
            newChat.push(<ChatRight data={sendData}/>);
        }
        this.setState({
            chat : newChat,
            input : ''
        });

        this.sendTextMessage();
    }

    onKeyup(e) {
        e.keyCode === 13 && this.send()
    }

    inputChange(event){
        this.setState({input : event.target.value});
    }

    componentDidUpdate(){
        this.refs.chat.scrollTop = this.refs.chat.scrollHeight - this.refs.chat.clientHeight;
    }

    componentWillMount(){
        let userId = this.props.match.params.id;

        get('/home/memberInfo' , {mem_id : userId} , function (error , data) {
            if(error === null) {
                if (data.code === 1) {
                    let RongIMLib = window.RongIMLib;

                    let appKey = "kj7swf8oki282";
                    let token = data.data.rongyun_token;
                    let config = {
                        // protobuf : "./protobuf-2.2.8.min.js"
                        protobuf : "//cdn.ronghub.com/protobuf-2.2.8.min.js"
                        // protobuf : "http(s)://cdn.ronghub.com/protobuf-2.2.8.min.js"
                    };
                    RongIMLib.RongIMClient.init(appKey,null,config);
                    let instance = RongIMLib.RongIMClient.getInstance();
                    // 连接状态监听器
                    RongIMLib.RongIMClient.setConnectionStatusListener({
                        onChanged: function (status) {
                            console.log(status);
                            switch (status) {
                                case RongIMLib.ConnectionStatus.CONNECTED:
                                    break;
                            }
                        }
                    });
                    RongIMLib.RongIMClient.setOnReceiveMessageListener({
                        // 接收到的消息
                        onReceived: function (message) {
                            switch (message.messageType) {
                                case RongIMLib.RongIMClient.MessageType.TextMessage:
                                    console.log(message.content.content);
                                    break;
                                default:
                                // do something...
                            }
                        }
                    });
                    //开始链接
                    RongIMLib.RongIMClient.connect(token, {
                        onSuccess: function(userId) {
                            //链接成功后 才可 发送消息
                            // document.getElementById("result").innerHTML += "链接成功，用户id：" + userId;
                            // sendTextMessage();
                        },
                        onTokenIncorrect: function() {
                            //console.log('token无效');
                        },
                        onError:function(errorCode){
                            console.log(errorCode);
                        }
                    });
                }
            }
        });

    }

    componentDidMount(){
        this.refs.chat.style.height = document.body.offsetHeight - this.refs.chatinput.offsetHeight + 'px';
        this.refs.chat.scrollTop = this.refs.chat.scrollHeight - this.refs.chat.clientHeight;
    }

    //发送消息定义
    sendTextMessage(){
        /*
         文档： http://www.rongcloud.cn/docs/web.html#5_1、发送消息
         http://rongcloud.cn/docs/api/js/TextMessage.html
         1: 单条消息整体不得大于128K
         2: conversatinType 类型是 number，targetId 类型是 string
         */
        let content = {
            content:"文字内容 content",
            extra:{
                "name":"name",
                "age" : 12
            }
        };
        let RongIMLib = window.RongIMLib;

        let conversationtype = RongIMLib.ConversationType.PRIVATE; // 私聊
        let msg = new RongIMLib.TextMessage(content);
        let targetId = "user10";
        let instance = RongIMLib.RongIMClient.getInstance();
        instance.sendMessage(conversationtype, targetId, msg, {
            onSuccess: function (message) {
                // document.getElementById("result").innerHTML += "<br>发送文字消息成功";
                console.log("发送文字消息成功");
                console.log(message);
            },
            onError: function (errorCode,message){
                console.log("发送文字消息失败");
                console.log(errorCode);
            }
        });
    }

    render() {
        return (
            <div className="chat-box" ref="chatBox">
                <div className="chat-info-box" ref="chat">
                    <div>
                        {
                            this.state.chat.map(function (chat) {
                              return chat
                            })
                        }
                    </div>
                </div>
                <div className="chat-input-box" ref="chatinput">
                    <Flex>
                        <Flex.Item className="chat-input"><input type="text" onKeyUp={this.onKeyup.bind(this)} onChange={this.inputChange.bind(this)} value={this.state.input}/></Flex.Item>
                        <Flex.Item className="chat-button-send"><button type="button" onClick={this.send.bind(this)}>发送</button></Flex.Item>
                    </Flex>
                </div>
            </div>
        );
    }
}

export default Chat;